﻿#region namespaces

using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;

#endregion

namespace GenericEncryptionClass
{
   public class GenericHashingAlgorithm
   {
      public static string CreateHash<T>(string source)
      where T : HashAlgorithm, new()
      {
         try
         {
            HashAlgorithm hashAlgorithm = new T();

            byte[] hashedBytes = hashAlgorithm.ComputeHash(Encoding.ASCII.GetBytes(source));

            return (Convert.ToBase64String(hashedBytes));
         }
         catch
         {
            return "Error while computing HASH!";
         }
      }

      public static string CreateHashFromFile<T>(string filePath)
      where T : HashAlgorithm, new()
      {
         FileStream fileStream = null;
         try
         {
            HashAlgorithm hashAlgorithm = new T();

            fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None);

            fileStream.Position = 0;

            byte[] hashedValue = hashAlgorithm.ComputeHash(fileStream);


            //hashAlgorithm.Dispose();

            return (Convert.ToBase64String(hashedValue));
         }
         catch
         {
            return "File does not exists!";
         }
         finally
         {
            if (fileStream != null)
               fileStream.Dispose();
         }
      }
   }
}